import axios from 'axios'

export const downloadFile = async (fileId) => {
  try {
    const response = await axios({
      method: 'get',
      url: `/api/files/download/${fileId}`,
      responseType: 'blob', // 关键：接收二进制数据
    })

    // 创建临时下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url

    // 从Content-Disposition获取文件名（后端需要设置响应头）
    const contentDisposition = response.headers['content-disposition']
    let fileName = 'unknown_file'
    if (contentDisposition) {
      const fileNameMatch = contentDisposition.match(/filename="?(.+)"?/)
      if (fileNameMatch.length > 1) fileName = fileNameMatch[1]
    }

    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('下载失败:', error)
    // 这里可以添加Ant Design的错误提示
  }
}
